import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
/**
 * 通过import 动态引入的代码。会有代码分割的功能（也就是熟称的路由懒加载）
 * 重定向，想让这个项目一进入页面就显示哪个具体指定的页面
 */
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home',
  },
  {
    path: '/layout',
    name: 'layout',
    meta: {
      auth: true,
      title: '首页',
    },
    component: () => import('../layouts/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          auth: true,
          title: '首页',
        },
        component: () => import('../views/Home.vue'),
      },
      {
        path: 'mine',
        name: 'mine',
        meta: {
          auth: true,
          title: '我的',
        },
        component: () => import('../views/Mine.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
      title: '登陆',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      auth: true,
      title: '搜索',
    },
    component: () => import('../views/SearchPage.vue'),
  },
  {
    path: '/readPage',
    name: 'readPage',
    meta: {
      auth: true,
      title: '读书页面',
    },
    component: () => import('../views/ReadPage.vue'),
  },
  {
    path: '/addComments/:id',
    name: 'addComments',
    meta: {
      auth: true,
      title: '关于',
    },
    component: () => import('../views/AddComments.vue'),
  },
  {
    path: '/detail/:id',
    name: 'detail',
    meta: {
      auth: true,
      title: '详情',
    },
    component: () => import('../views/Detail.vue'),
  },
]

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 1. 导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    // 需要守卫, 找token
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/login',
      })
    }
  } else {
    next()
  }
})
export default router
